import React, { Component } from 'react'
import { Row, Col, Tree, Tooltip, Input, Button, Empty, message, Pagination } from 'antd';
import styles from './index.less';
import { history } from 'umi'
import { StarFilled } from '@ant-design/icons';
import { getMateriale, collectCourseware } from '@/services/learnStudent'
import { fileurl} from '@/services/baseurl'
function againGroup(data:any, num:number) {
    const  result = [];
    for (let i = 0, len = data.length; i < len; i += num) {
        result.push(data.slice(i, i + num));
    }
    return result;

}
export default class Courseware extends Component<any, any> {
    constructor(props: any) {
        super(props)
        this.state = {
            subject: '',
            listData: [],
            name: '',
            treeData: [],
            count: 1,
            currentPage:0,
        }
    }

    collectHandle = (e: any, item: any) => {
        const uid = localStorage.getItem('id') || '';
        e.nativeEvent.stopImmediatePropagation()
        e.stopPropagation();
        const { subject } = this.state;
        collectCourseware({ collect: item.id, uid }).then(res => {
            if (res.status === 1) {
                message.success('操作成功')
                this.renderList(subject)
            } else {
                message.error('操作失败')
            }
        })
    }
    openFile = (item: any) => () => {
        localStorage.setItem('doc', item.doc)
        history.push('/file/' + item.id+'/'+(item.is_jc||0))
    }
    selectSubject = (e: any) => {
        if (e[0]) {
            this.setState({
                subject: e[0]
            })
        }
        history.push('/train?tab=2&subject='+e[0])
        this.renderList(e[0] || '')
    }
    changeName = (e: any) => {
        this.setState({
            name: e.target.value
        })
    }
    renderList = (subject: string) => {
        const { name } = this.state;
        const uid = localStorage.getItem('id') || '';
        if (!subject) return;
        getMateriale({ subject, name, uid }).then(res => {
            if (res[0]) {
                    
                this.setState({
                    listData: againGroup(res,6),
                    count: res.length
                })
            } else {
                this.setState({
                    listData: []
                })
            }
        })
    }
    searchHandle = () => {
        const { subject } = this.state;
        this.renderList(subject)
    }
    componentDidMount() {
        const info = JSON.parse(localStorage.getItem('userinfo') || '{}').subject.split(',')
        const {subject} = this.props.params;
        this.setState({
            subject: subject?Number(subject):info[0]
        })
        this.renderList(subject?Number(subject):info[0])
    }
    changePage=(e)=>{
        this.setState({
            currentPage:e-1
        })
    }

    render() {
        const { listData, subject, count ,currentPage} = this.state;
        const { treeData } = this.props;
        return (
            <Row>
                <Col span={4}>
                    <Tree treeData={treeData} selectedKeys={[subject]} onSelect={this.selectSubject} />
                </Col>
                <Col span={20}>
                    <div className={styles['search-area']}>
                        <Button type="primary" style={{ float: 'right' }} onClick={this.searchHandle}>搜索</Button>
                        <Input style={{ width: 200, marginRight: 10, float: 'right' }} onChange={this.changeName} placeholder="请输入搜索内容"></Input>
                    </div>
                    <div style={{width:'100%',overflow:'hidden'}}>
                        {listData[currentPage] ? listData[currentPage].map((item: any) => {
                            const isCollect = item.is_collect === 1;
                            const color = isCollect ? 'orange' : '#ccc';
                            return item && <div key={item.id} className={`${styles['collect-cards']} ${styles['video-cards']}`} onClick={this.openFile(item)}>
                                <img src={fileurl(item.is_jc) + item.cover} alt="" />
                                <div>
                                    <div >
                                        <h4>{item.name}</h4>
                                        <p>编辑日期：{item.created_at}</p>
                                    </div>
                                    <Tooltip title={isCollect ? '取消收藏' : '收藏'}><StarFilled onClick={(e) => this.collectHandle(e, item)} style={{ color: "#f60" }} style={{ color }} className={styles['courseware-cards-collect']} /></Tooltip>
                                </div>
                            </div>
                        }) : <Empty />}
                    </div>
                    <Pagination style={{ float: 'right' }} onChange={this.changePage} showQuickJumper total={count} pageSize={6} showTotal={(total, range) => `第${range[0]}条-第${range[1]}条，共 ${total} 条`} />
                </Col>

            </Row>
        )
    }
}
